package com.gy.controller.research;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.research.Horizontal;
import com.gy.entity.research.Longitudinal;
import com.gy.query.HorizontalQuery;
import com.gy.query.LongitudinalQuery;
import com.gy.result.Result;
import com.gy.service.HorizontalService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.HorizontalVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/horizontal")
@Api(tags = "横向课题接口")
@CrossOrigin
public class HorizontalController {

    @Autowired
    private HorizontalService horizontalService;
    /**
     * 根据openid分页查看某个人的横向课题
     */
    @PostMapping("/get/certification")
    @ApiOperation("根据openid查看某个人的横向课题材料")
    public Result<PageVO<Horizontal>> getPapers(@RequestBody HorizontalQuery horizontalQuery){
        return horizontalService.getHorizontal(horizontalQuery);
    }

    /**
     * 根据横向课题id主键删除横向课题
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据其他id主键删除横向课题")
    public Result deleteById(@PathVariable Long id){
        return horizontalService.removeHorizontalById(id);
    }

    /**
     * 根据id主键查看横向课题
     */
    @GetMapping("/getById/{id}")
    @ApiOperation("根据id主键查看横向课题")
    public Result<Horizontal> getHorizontalById(@PathVariable Long id) {
        Horizontal horizontal = horizontalService.getHorizontalById(id);
        if (horizontal == null) {
            return Result.error("横向课题未找到");
        }
        return Result.success(horizontal);
    }

    /**
     * 更改横向课题资料
     */
    @PutMapping("/update")
    @ApiOperation("更改横向课题资料")
    public Result update(@RequestBody Horizontal horizontal) {
        return horizontalService.updateHorizontal(horizontal);
    }

    /**
     * 新增横向课题资料
     */
    @PostMapping("/save")
    @ApiOperation("新增横向课题资料")
    public Result addHorizontal(@RequestBody Horizontal horizontal) {
        Result result = horizontalService.saveHorizontal(horizontal);
        return result;
    }

    /**
     * 根据多个id查询横向课题
     */
    @PostMapping("/getHorizontalByIds")
    @ApiOperation("通过多个id查询横向课题信息")
    public Result getHorizontalByIds(@RequestBody Long[] ids) {
        // Validate the input IDs
        if (ids == null || ids.length == 0) {
            return Result.error("未提供有效的横向课题ID");
        }

        // Call the service method to retrieve Horizontal entities by IDs
        return horizontalService.getHorizontalByIds(ids);
    }

    /**
     * excel批量导出横向课题资料
     */
    @PostMapping("/export")
    @ApiOperation("批量导出横向课题资料")
    public void exportHorizontal(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();  // 获取字段信息
        List<Map<String, Object>> data = request.getData();  // 获取数据内容

        String fileName = "exported_Horizontal.xlsx";  // 设置导出文件的名称
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 使用 EasyExcel 写入数据到响应流
        EasyExcel.write(response.getOutputStream())
                .head(head)  // 设置表头
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("横向课题资料")  // 设置工作表名
                .doWrite(transformedData);  // 写入数据
    }
    /**
     * 获取横向课题汇总
     */
    @GetMapping("/getSummary")
    @ApiOperation("获取横向课题汇总")
    public Result<List<HorizontalVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询横向课题数据
        List<Horizontal> horizontalList = horizontalService.lambdaQuery()
                .eq(Horizontal::getUserId, userId)
                .select(Horizontal::getProjectName, Horizontal::getContractSource, Horizontal::getContractNumber,
                        Horizontal::getRank, Horizontal::getFundingAmount, Horizontal::getStartTime,
                        Horizontal::getEndTime, Horizontal::getProjectStatus)
                .list();

        // 将 Horizontal 转换为 HorizontalVO
        List<HorizontalVO> horizontalVOList = horizontalList.stream()
                .map(horizontal -> HorizontalVO.builder()
                        .projectName(horizontal.getProjectName())
                        .contractSource(horizontal.getContractSource())
                        .contractNumber(horizontal.getContractNumber())
                        .rank(horizontal.getRank())
                        .fundingAmount(horizontal.getFundingAmount())
                        .startTime(horizontal.getStartTime())
                        .endTime(horizontal.getEndTime())
                        .projectStatus(horizontal.getProjectStatus())
                        .build())
                .collect(Collectors.toList());

        return Result.success(horizontalVOList);
    }
}
